#include <smartHome/smartHome.h>
SmartHome::SmartHome():
    IAgentComponent(AgentComponentType::GUI,false),
    Config("resource/config/smartHome.json"){
    dev = getValue("dev").asString();
}
void SmartHome::Init(){
    
}
void SmartHome::PollMessage(Message message){
    if(message.fromType == AgentComponentType::NLP){
        string type = message.content.at(0);
        if(type == "light_smartHome"){
            Json::Reader reader;
            Json::Value root;
            reader.parse(message.content.at(1),root,false);
            root = root["intent"]["semantic"]["slots"]["attrValue"];
            cout<<root.asString()<<endl;
            if(root.asString() == "开")SetLight(true);
            if(root.asString() == "关")SetLight(false);
        }
    }
}
int SmartHome::set_interface_attribs(int fd, int speed)
{
    struct termios tty;

    if (tcgetattr(fd, &tty) < 0) {
        printf("Error from tcgetattr: %s\n", strerror(errno));
        return -1;
    }

    cfsetospeed(&tty, (speed_t)speed);
    cfsetispeed(&tty, (speed_t)speed);

    tty.c_cflag |= (CLOCAL | CREAD);    /* ignore modem controls */
    tty.c_cflag &= ~CSIZE;
    tty.c_cflag |= CS8;         /* 8-bit characters */
    tty.c_cflag &= ~PARENB;     /* no parity bit */
    tty.c_cflag &= ~CSTOPB;     /* only need 1 stop bit */
    tty.c_cflag &= ~CRTSCTS;    /* no hardware flowcontrol */

    /* setup for non-canonical mode */
    tty.c_iflag &= ~(IGNBRK | BRKINT | PARMRK | ISTRIP | INLCR | IGNCR | ICRNL | IXON);
    tty.c_lflag &= ~(ECHO | ECHONL | ICANON | ISIG | IEXTEN);
    tty.c_oflag &= ~OPOST;

    /* fetch bytes as they become available */
    tty.c_cc[VMIN] = 1;
    tty.c_cc[VTIME] = 1;

    if (tcsetattr(fd, TCSANOW, &tty) != 0) {
        printf("Error from tcsetattr: %s\n", strerror(errno));
        return -1;
    }
    return 0;
}
void SmartHome::set_mincount(int fd, int mcount)
{
    struct termios tty;

    if (tcgetattr(fd, &tty) < 0) {
        printf("Error tcgetattr: %s\n", strerror(errno));
        return;
    }

    tty.c_cc[VMIN] = mcount ? 1 : 0;
    tty.c_cc[VTIME] = 5;        /* half second timer */

    if (tcsetattr(fd, TCSANOW, &tty) < 0)
        printf("Error tcsetattr: %s\n", strerror(errno));
}
void SmartHome::SetLight(bool mode){
    if(fd==0)fd = open(dev.c_str(), O_RDWR | O_NOCTTY | O_SYNC | O_NONBLOCK);
    if (fd < 0) {
        cout<<"fuck"<<endl;
        return;
    }
    set_interface_attribs(fd, B9600);
    int x = mode?79:70;
    write(fd, &x, sizeof(x));
    tcdrain(fd);
    //close(fd);
}